/**
 * 调试工具库
 * 提供各种调试辅助功能
 */

/**
 * 检查图片的Base64数据是否有效
 * @param {string} base64Data - Base64编码的图片数据
 * @returns {object} 检查结果
 */
function showImageDebugInfo(base64Data) {
  const result = {
    isValid: false,
    length: 0,
    type: 'unknown',
    hasPrefix: false,
    message: ''
  };
  
  if (!base64Data) {
    result.message = '图片数据为空';
    return result;
  }
  
  result.length = base64Data.length;
  result.type = typeof base64Data;
  
  if (typeof base64Data !== 'string') {
    result.message = `图片数据类型错误: ${result.type}，应为string`;
    return result;
  }
  
  // 检查前缀
  if (base64Data.startsWith('data:image/')) {
    result.hasPrefix = true;
  }
  
  // 基本有效性检查
  if (base64Data.length > 100) {
    result.isValid = true;
    result.message = '图片数据有效';
  } else {
    result.message = '图片数据长度异常，可能无效';
  }
  
  return result;
}

/**
 * 显示API请求的关键信息，用于调试
 * @param {string} url - API请求地址
 * @param {object} data - 请求数据
 * @returns {object} 处理后的调试信息
 */
function showApiRequestInfo(url, data) {
  // 创建简化版的请求数据副本，排除敏感数据
  const sanitizedData = { ...data };
  
  // 如果包含图片数据，只保留长度信息
  if (sanitizedData.imageBase64 || sanitizedData.base64Image || sanitizedData.image) {
    if (sanitizedData.imageBase64) {
      sanitizedData.imageBase64 = `[Base64 image data, length: ${sanitizedData.imageBase64.length}]`;
    }
    if (sanitizedData.base64Image) {
      sanitizedData.base64Image = `[Base64 image data, length: ${sanitizedData.base64Image.length}]`;
    }
    if (sanitizedData.image) {
      sanitizedData.image = `[Base64 image data, length: ${sanitizedData.image.length}]`;
    }
  }
  
  return {
    url: url,
    endpoint: url.split('/').pop(),
    requestData: sanitizedData,
    timestamp: new Date().toISOString()
  };
}

/**
 * 简单的性能计时器
 */
class PerformanceTimer {
  constructor(name) {
    this.name = name;
    this.startTime = Date.now();
    this.marks = {};
    console.log(`[Timer] ${name} 开始计时`);
  }
  
  mark(label) {
    const elapsed = Date.now() - this.startTime;
    this.marks[label] = elapsed;
    console.log(`[Timer] ${this.name} - ${label}: ${elapsed}ms`);
    return elapsed;
  }
  
  end() {
    const totalTime = Date.now() - this.startTime;
    console.log(`[Timer] ${this.name} 结束，总耗时: ${totalTime}ms`);
    
    // 返回完整计时信息
    return {
      name: this.name,
      total: totalTime,
      marks: this.marks
    };
  }
}

module.exports = {
  showImageDebugInfo,
  showApiRequestInfo,
  PerformanceTimer
};
